package SmartFleet.station;

import java.util.Timer;

import linker.ClientLinker;
import linker.exception.CanNotCreateSocketException;
import linker.exception.CanNotReadObjectException;
import linker.exception.CanNotWriteObjectException;
import smartfleet.communication.stationrwprotocol.StationInfo;
import smartfleet.communication.stationrwprotocol.StationLoginResponse;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class LoginService extends Service {
	
	private static SmartFleetStation	MAIN_ACTIVITY;
	
	private ClientLinker				client;
	
	private String						ip		= "194.210.228.119";	// Server
																		// IP
	private int							port	= 6780;				// Server
																		// port
	private Timer						timer	= new Timer();
	
	private void loginStation() {

		try {
			
			this.client = new ClientLinker(this.ip, this.port);
			
			MAIN_ACTIVITY.getMyStation().setPort(3333);
			StationInfo login = new StationInfo(MAIN_ACTIVITY.getMyStation().getId(), MAIN_ACTIVITY.getMylocation().getLatitudeE6(), MAIN_ACTIVITY.getMylocation().getLongitudeE6(), this.ip, 3333);
			StationLoginResponse resp = LoginToRW(login);
			MAIN_ACTIVITY.setId(resp.getId());
			
		} catch (CanNotCreateSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private StationLoginResponse LoginToRW(StationInfo login) {

		// TODO Auto-generated method stub
		
		StationLoginResponse response = null;
		
		try {
			
			this.client.writeObject(login);
			
			response = (StationLoginResponse) this.client.readObject();
			
		} catch (CanNotWriteObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CanNotReadObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return response;
		
	}
	
	private void stopservice() {

		if (this.timer != null)
			this.timer.cancel();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}
	
	@Override
	public void onCreate() {

		super.onCreate();
		loginStation();
	}
	
	@Override
	public void onDestroy() {

		super.onDestroy();
		stopservice();
	}
	
	public static void setMainActivity(SmartFleetStation activity) {

		MAIN_ACTIVITY = activity;
	}
}